package com.lxg.controller.firstController;

import com.lxg.dao.AdminDao;
import com.lxg.dao.UserDao;
import com.lxg.pojo.Admin;
import com.lxg.pojo.User;
import com.lxg.service.firstService.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    AdminDao adminDao;
    @Autowired
    UserDao userDao;

    @RequestMapping(value = "/loginSuccess",method = RequestMethod.POST)
    public String loginSuccess(HttpServletRequest req, HttpSession session) {

        session.removeAttribute("flag1");

        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        String radio = req.getParameter("radio");

        System.out.println(radio);

        if (radio != null && radio.equals("admin")) {
            boolean a = loginService.adminLogin(username, password);
            if (a) {
                //管理员验证成功
                Admin loginUser = adminDao.getAdmin(username, password);
                //保存用户信息到Session域中
                session.setAttribute("user", loginUser);
                session.setAttribute("name",username);

                session.setAttribute("identity","图书管理员");

                return "redirect:/admin/home";
            } else {
                req.setAttribute("login_msg", "用户或密码错误！");
                req.setAttribute("username", username);
                //   跳回登录页面
                return "/first/login";
            }
        } else if (radio != null && radio.equals("reader")) {
            boolean u = loginService.userLogin(username, password);
            if (u) {
                //用户验证成功
                User loginUser = userDao.getUser(username, password);
                //保存用户信息到Session域中
                session.setAttribute("user", loginUser);
                session.setAttribute("name",username);
                session.setAttribute("identity","普通用户");
                return "redirect:/";
            } else {
                // 把错误信息，和回显的表单项信息，保存到Request域中
                req.setAttribute("login_msg", "用户或密码错误！");
                req.setAttribute("username", username);
                return "/first/login";
            }
        }
        return "/first/login";
    }
}
